home *** CD-ROM | disk | FTP | other *** search
/ Skunkware 98 / Skunkware 98.iso / osr5 / sco / scripts / admin / checkown < prev    next >
Encoding:
AWK Script  |  1997-08-26  |  40.4 KB  |  1,101 lines

  1. #!/usr/local/bin/gawk -f
  2. # @(#) checkown.gawk 1.2 97/02/06
  3. # 96/08/18 john h. dubois iii (john@armory.com)
  4. # 96/11/18 Added lbnx options.  Made command line args work.
  5. #          Work for filenames that include path.
  6. # 97/02/06 Added p option.
  7.  
  8. BEGIN {
  9.     Name = "checkown"
  10.     Usage = "Usage: " Name " [-hlbn] [-p<number>] [-u<minuid>] [file ...]"
  11.     ARGC = Opts(Name,Usage,"hlbnxu>p>",0)
  12.     if ("h" in Options) {
  13.     printf \
  14. "%s: Check files that should have the same name as their owner.\n"\
  15. "%s\n"\
  16. "Any file not owned by a user with the same name as the file is warned\n"\
  17. "about.  Files with names that could not be user names are ignored.  If no\n"\
  18. "filenames are given on the command line, they are read from the standard\n"\
  19. "input, one per line.\n"\
  20. "Options:\n"\
  21. "-h: Print this help.\n"\
  22. "-l: Print initial messages to the error output, and at the end of\n"\
  23. "    processing, print a line that contains all of the filenames to the\n"\
  24. "    standard output.\n"\
  25. "-n: Emit problem filenames only.\n"\
  26. "-p<number>: Split each filename read into fields separated by strings of\n"\
  27. "    characters that cannot be part of a user name, and take the user name\n"\
  28. "    to be the <number>'th field, with field numbers starting at 1.  If a\n"\
  29. "    filename begins with a leading string of characters that cannot be\n"\
  30. "    part of a user name, the field that comes after it is field 1.  The\n"\
  31. "    characters that may be part of a username are - (hyphen), a-z, and 0-9.\n"\
  32. "    Example: In the filename .spcecdt.pop, field 1 is \"spcecdt\" and field\n"\
  33. "    2 is \"pop\".  To process filenames of this type, -p1 would be used.\n"\
  34. "-u<minuid>: Do not complain about files owned by UIDs less than <minuid>.\n"\
  35. "-b: Complain about files with names that cannot be user names.  A user name\n"\
  36. "    must consist of characters from the set described for -p, must be 2 to\n"\
  37. "    8 characters long, and must begin with a letter.\n",
  38.     Name,Usage
  39.     exit 0
  40.     }
  41.     minUID = "u" in Options ? Options["u"] : 0
  42.     Debug = "x" in Options
  43.     messages = "l" in Options ? "/dev/stderr" : "/dev/stdout"
  44.     namesOnly = "n" in Options
  45.     nameCheck = "b" in Options
  46.     if ("p" in Options)
  47.     nameField = Options["p"]
  48.     statCmd = "stat -Lnu"
  49.     if (ARGC > 1)
  50.     statCmd = statCmd " " QuoteArgs(ARGV,1,ARGC-1)
  51.     else
  52.     statCmd = statCmd " -r"
  53.     if (Debug)
  54.     printf "stat command: %s\n",statCmd > "/dev/stderr"
  55.     ReadPasswd()    # set up PW_vars
  56.     while ((statCmd | getline) == 1) {
  57.     tail = file = $1
  58.     sub(".*/","",tail)
  59.     uid = $2
  60.     if (nameField) {
  61.         n = split(tail,elem,/[^-a-z0-9]+/)
  62.         i = (elem[1] == "") ? nameField+1 : nameField
  63.         if (i > n) {
  64.         if (nameCheck) {
  65.             if (namesOnly)
  66.             print file > messages
  67.             else
  68.             printf "Not enough fields in filename (need %d): %s)\n",
  69.             nameField,file > messages
  70.             names = names " " file
  71.         }
  72.         continue
  73.         }
  74.         tail = elem[i]
  75.     }
  76.     if (length(tail) <= 8 && tail ~ /^[a-z][-a-z0-9]+$/) {
  77.         if (uid < minUID)
  78.         continue
  79.         filenameUID = getpwnam(tail,PWEnt,PW_UID) 
  80.         if (filenameUID != uid) {
  81.         if (Debug)
  82.             printf \
  83.             "filename: <%s> owner-uid: <%s> owner-name: <%s>\n",
  84.             file,uid,filenameUID > "/dev/stderr"
  85.         Owner = getpwuid(uid,PWEnt,PW_NAME)
  86.         if (Owner == ":")
  87.             Owner = uid
  88.         if (namesOnly)
  89.             print file > messages
  90.         else
  91.             printf "Owner of %s is %s%s\n",file,Owner,
  92.             (filenameUID == ":") ? " (no user '" tail "')" : "" \
  93.             > messages
  94.         names = names " " file
  95.         }
  96.     }
  97.     else if (nameCheck) {
  98.         if (namesOnly)
  99.         print file > messages
  100.         else {
  101.         printf "Filename component cannot be user name: %s\n",
  102.         tail > messages
  103.         if (tail != file)
  104.             printf "Full filename: %s\n",file > messages
  105.         }
  106.         names = names " " file
  107.     }
  108.     }
  109.     if ("l" in Options && names != "")
  110.     print substr(names,2)
  111. }
  112.  
  113. ### Begin pwent library
  114.  
  115. # @(#) pwent.awk 1.2 96/06/27
  116. # 92/08/10 john h. dubois III (john@armory.com)
  117. # 93/12/13 fixed to not clobber $*
  118. # 96/01/05 Send error messages to /dev/stderr
  119. # 96/05/24 Let getpwnam() return a specific field if requested.
  120. #          Added PW_REAL and PW_OFFICE.
  121. # 96/06/03 Added Type field to getpwent()
  122. # 96/06/24 Allow a Field to be requested for getpwent() also.
  123. # 96/06/29 Added PW_RECORD, and getpwreal().
  124. #          Changed PWLines to be index by record number instead of name.
  125. # 96/11/17 Added getpwuid()
  126.  
  127. # Require: ReadShells()
  128.  
  129. # getpwent, getpwnam: get an entry from the passwd file.
  130. # Each of the following passwd functions returns an array which contains
  131. # a passwd file entry.  The array contains the fields of the entry.
  132. # Global variables:
  133. # The following variables are defined with the values of the indexes of the
  134. # entries: PW_NAME, PW_PASSWORD, PW_UID, PW_GID, PW_GCOS, PW_HOME, PW_SHELL
  135. # PWLines[] contains the lines of the password file, indexed by record number,
  136. # starting with 1.
  137. # _pwNames[] is a mapping of name to passwd record number.
  138. # getpwentNum is the number of the next entry to be returned by getpwent().
  139.  
  140. # Left FS global because making it local does not work in gawk.
  141. function ReadPasswd(  User,Line,i,Ind,ret,OFS) {
  142.     if (PW_Name)
  143.     return 1
  144.     PW_NAME = 1
  145.     PW_PASSWORD = 2
  146.     PW_UID = 3
  147.     PW_GID = 4
  148.     PW_GCOS = 5
  149.     PW_HOME = 6
  150.     PW_SHELL = 7
  151.     PW_REAL = -1    # for PWGetFields()
  152.     PW_OFFICE = -2
  153.     PW_RECORD = -3
  154.  
  155.     Ind = getpwentNum = 1
  156.     OFS = FS
  157.     FS = ":"
  158.     while ((ret = (getline Line < "/etc/passwd")) == 1) {
  159.     User = Line
  160.     sub(":.*","",User)
  161.     _pwNames[User] = Ind
  162.     PWLines[Ind++] = Line
  163.     }
  164.     FS = OFS
  165.     close("/etc/passwd")
  166.     if (ret) {
  167.     printf "ReadPasswd(): Could not open /etc/passwd.\n" > "/dev/stderr"
  168.     return 0
  169.     }
  170.     return 1
  171. }
  172.  
  173. # setpwent resets the passwd file entry pointer used by getpwent
  174. # to the first entry.
  175. function setpwent() {
  176.     getpwentNum = 1
  177. }
  178.  
  179. # getpwent sets PWEnt to the next entry in the passwd file.
  180. # If Type is set to -1, the entry for the next "real" user is returned (others
  181. # are skipped over), where a real user is a user whose login shell is listed in
  182. # /etc/shells.  This requires the ReadShells() function.  Other values for
  183. # Type are not yet defined and are ignored.
  184. # If the last entry has already been returned, 0 is return if Field is null,
  185. # ":" if not.
  186. # If the entry for the next real user has been requested and /etc/shells
  187. # cannot be read, -1 is returned if Field is null, "\n" if not.
  188. # See PWGetFields() for other return values and the meaning of the Field
  189. # parameter.
  190. function getpwent(PWEnt,Type,Field,  entNum) {
  191.     if (!PW_NAME)
  192.     ReadPasswd()
  193.     if (!(getpwentNum in PWLines))
  194.     return Field ? ":" : 0
  195.     if (Type == -1) {
  196.     if (!_DidReadShells && ReadShells(LoginShells) == -1)
  197.         return Field ? "\n" : -1
  198.     split(PWLines[getpwentNum++],PWEnt,":")
  199.     while (!(PWEnt[PW_SHELL] in LoginShells)) {
  200.         if (!(getpwentNum in PWLines))
  201.         return Field ? ":" : 0
  202.         split(PWLines[getpwentNum++],PWEnt,":")
  203.     }
  204.     return PWGetFields("",PWEnt,Field,getpwentNum - 1)
  205.     }
  206.     else {
  207.     entNum = getpwentNum
  208.     return PWGetFields(PWLines[getpwentNum++],PWEnt,Field,entNum)
  209.     }
  210. }
  211.  
  212. function MakeInd(  Elem,Ind,Line,uid,home) {
  213.     for (Ind = 1; Ind in PWLines; Ind++) {
  214.     Line = PWLines[Ind]
  215.     split(Line,Elem,":")
  216.     uid = Elem[PW_UID]
  217.     if (!(uid in uidInd))
  218.         uidInd[uid] = Ind
  219.     home = Elem[PW_HOME]
  220.     if (!(home in HomeInd))
  221.         HomeInd[home] = Ind
  222.     }
  223.     IndDone = 1
  224. }
  225.  
  226. # PWGetFields() splits PWLine into PWEnt[], and optionally returns a field
  227. # from it.  If PWLine is null, PWEnt[] is assumed to have already been filled
  228. # in with a password entry.
  229. # If Field is not passed or is null, the return value is 1.
  230. # If Field is non-null, it should a PW_ value.  In this case, the value of the
  231. # requested field is returned.
  232. # entNum is the value that PWEnt[PW_RECORD] should be set to.  It should be
  233. # the index in PWLines[] of the record being processed.
  234. # In addition to the PW_ values used by the rest of the functions in this
  235. # library, this function can be passed PW_REAL and PW_OFFICE.
  236. # PW_REAL will get the part of the GCOS field before the first comma.
  237. # PW_OFFICE will get the part of the GCOS field after the first comma.
  238. # If either of these is requested, both values will also be assigned to their
  239. # indices in PWEnt[], unless there is no comma in the GCOS field, in which case
  240. # PW_OFFICE will not be set.
  241. # NOTE: since the global field names are set in ReadShells(), it must be
  242. # executed before any of the field name can be passed.
  243. function PWGetFields(PWLine,PWEnt,Field,entNum,  gcos,ind) {
  244.     if (PWLine != "")
  245.     split(PWLine,PWEnt,":")
  246.     PWEnt[PW_RECORD] = entNum
  247.     if (!Field)
  248.     return 1
  249.     if (Field < 0) {
  250.     if (ind = index(gcos = PWEnt[PW_GCOS],",")) {
  251.         PWEnt[PW_OFFICE] = substr(gcos,ind+1)
  252.         PWEnt[PW_REAL] = substr(gcos,1,ind-1)
  253.     }
  254.     else
  255.         PWEnt[PW_REAL] = gcos
  256.     }
  257.     return PWEnt[Field]
  258. }
  259.  
  260. # getpwnam sets PWEnt to the passwd entry for login name Name.
  261. # If Name does not exist in the password file, the return value is ":"
  262. # if Field was passed, 0 if not.
  263. # For other return values and parameter explanation, see PWGetFields()
  264. function getpwnam(Name,PWEnt,Field) {
  265.     if (!PW_NAME)
  266.     ReadPasswd()
  267.     if (Name in _pwNames)
  268.     return PWGetFields(PWLines[_pwNames[Name]],PWEnt,Field,_pwNames[Name])
  269.     else
  270.     return Field ? ":" : 0
  271. }
  272.  
  273. # getpwhome sets PWEnt to the passwd entry whose home dir is Home.
  274. # See getpwnam() for return values and the meaning of the Field param.
  275. function getpwhome(Home,PWEnt,Field) {
  276.     if (!PW_NAME)
  277.     ReadPasswd()
  278.     if (!IndDone)
  279.     MakeInd()
  280.     if (Home in HomeInd)
  281.     return PWGetFields(PWLines[HomeInd[Home]],PWEnt,Field,HomeInd[Home])
  282.     else
  283.     return Field ? ":" : 0
  284. }
  285.  
  286. # getpwuid sets PWEnt to the passwd entry whose uid is UID.
  287. # See getpwnam() for return values and the meaning of the Field param.
  288. function getpwuid(UID,PWEnt,Field) {
  289.     if (!PW_NAME)
  290.     ReadPasswd()
  291.     if (!IndDone)
  292.     MakeInd()
  293.     if ((UID + 0) in uidInd)
  294.     return PWGetFields(PWLines[uidInd[UID]],PWEnt,Field,uidInd[UID])
  295.     else
  296.     return Field ? ":" : 0
  297. }
  298.  
  299. # Make an index by real name.  For each passwd file entry, the real-name
  300. # is lowercased and split into components on non-alphanums.   The passwd entry
  301. # index that the name came from is added to the value of each such component
  302. # in the global _RealInd[].  The indexes stored this way are separated by
  303. # commas.  If the real-name contains no alphanums, its index is stored under
  304. # the null index.
  305. function _makeRealInd(  PWEnt,ret,Elem,nelem,i,Component) {
  306.     setpwent()
  307.     while ((ret = getpwent(PWEnt,"",PW_REAL)) != ":") {
  308.     nelem = split(tolower(ret),Elem,/[^a-z0-9]+/)
  309.     for (i = 1; i <= nelem; i++) {
  310.         Component = Elem[i]
  311.         if (Component == "" && nelem > 1)
  312.         continue
  313.         if (Component in _RealInd)
  314.         _RealInd[Component] = _RealInd[Component] "," PWEnt[PW_RECORD]
  315.         else
  316.         _RealInd[Component] = PWEnt[PW_RECORD]
  317.     }
  318.     }
  319.     _realIndDone = 1
  320. }
  321.  
  322. # Make Name into a pattern that will match a name that contains all of the
  323. # same name components (sequences of alphanums) in the same order.  If Name
  324. # contains no name components, a null string is returned.
  325. function MakeNamePat(Name,  Elem,nelem,i,Pat,e) {
  326.     nelem = split(Name,Elem,/[^a-zA-Z0-9]+/)
  327.     for (i = 1; i <= nelem; i++) {
  328.     if ((e = Elem[i]) == "")
  329.         continue
  330.     if (Pat == "")
  331.         Pat = "(^|[^a-zA-Z0-9])" e
  332.     else
  333.         Pat = Pat "[^a-zA-Z0-9](.*[^a-zA-Z0-9])?" e
  334.     }
  335.     if (Pat == "")    # If Name contained no alphanums...
  336.     return ""
  337.     Pat = Pat "([^a-zA-Z0-9]|$)"
  338.     return Pat
  339. }
  340.  
  341. # getpwgreal sets PWEnt to the first passwd entry whose PW_REAL (see
  342. # PWGetFields()) field matches Real.  Matching occurs if the alphanumeric
  343. # components of Real occur in the same order in the entry.  Non-alphanums are
  344. # ignored.  All of the components in Real must occur in the entry, but not all
  345. # of the components in the entry must occur in Real.
  346. # If the given name does not exist in the password file,
  347. # the return value is ":" if Field was passed, 0 if not.
  348. # If Next is true, getpwreal() sets PWEnt to the next passwd entry whose
  349. # PW_REAL field matches the last previous Real parameter passed.
  350. # In this case,  if the last entry has already been returned,
  351. # the return value is ":" if Field was passed, 0 if not.
  352. # Different IgnoreCase and Full parameters may be given when doing a Next
  353. # search.  Both must always be passed; they do not default to the original
  354. # values when doing a Next search.  The only parameter ignored when doing a
  355. # Next search is Real.
  356. # If IgnoreCase is true, case is ignored when searching.
  357. # If Full is true, a match of the full name is required (including any
  358. # punctuation).
  359. # For successful return values and Field parameter explanation,
  360. # see PWGetFields()
  361. # Globals: For the Next search, between invokations these varies store values:
  362. # _getpwrealInd[]: The set of pw indices that matched the query.
  363. # _getpwrealIndInd: The next index in _getpwrealInd[] to look at.
  364. # _getpwrealReal: The Real value passed with the original query.
  365. # _getpwrealPat: Real converted to a component order search pattern.
  366. function getpwreal(Real,PWEnt,Field,IgnoreCase,Full,Next,  ind,name,Pat) {
  367.     if (!Next) {
  368.     if (!PW_NAME)
  369.         ReadPasswd()
  370.     if (!_realIndDone)
  371.         _makeRealInd()
  372.     _getpwrealReal = Real
  373.     _getpwrealPat = MakeNamePat(Real)
  374.     # Get first component from Real
  375.     Real = tolower(Real)
  376.     gsub("^[^a-z0-9]+","",Real)
  377.     gsub("[^a-z0-9].*","",Real)
  378.     if (!(Real in _RealInd))
  379.         return Field ? ":" : 0
  380.     split(_RealInd[Real],_getpwrealInd,",")
  381.     _getpwrealIndInd = 1
  382.     }
  383.     if (Full)
  384.     Pat = _getpwrealReal
  385.     else
  386.     Pat = _getpwrealPat
  387.     if (IgnoreCase)
  388.     Pat = tolower(Pat)
  389.     while (_getpwrealIndInd in _getpwrealInd) {
  390.     ind = _getpwrealInd[_getpwrealIndInd++]
  391.     name = PWGetFields(PWLines[ind],PWEnt,PW_REAL,ind)
  392.     if (IgnoreCase)
  393.         name = tolower(name)
  394.     if (Full ? (name == Pat) : (name ~ Pat))
  395.         return PWGetFields("",PWEnt,Field,ind)
  396.     }
  397.     return Field ? ":" : 0
  398. }
  399.  
  400. ### End pwent library
  401. ### Start of ProcArgs library
  402. # @(#) ProcArgs 1.11 96/12/08
  403. # 92/02/29 john h. dubois iii (john@armory.com)
  404. # 93/07/18 Added "#" arg type
  405. # 93/09/26 Do not count -h against MinArgs
  406. # 94/01/01 Stop scanning at first non-option arg.  Added ">" option type.
  407. #          Removed meaning of "+" or "-" by itself.
  408. # 94/03/08 Added & option and *()< option types.
  409. # 94/04/02 Added NoRCopt to Opts()
  410. # 94/06/11 Mark numeric variables as such.
  411. # 94/07/08 Opts(): Do not require any args if h option is given.
  412. # 95/01/22 Record options given more than once.  Record option num in argv.
  413. # 95/06/08 Added ExclusiveOptions().
  414. # 96/01/20 Let rcfiles be a colon-separated list of filenames.
  415. #          Expand $VARNAME at the start of its filenames.
  416. #          Let varname=0 and -option- turn off an option.
  417. # 96/05/05 Changed meaning of 7th arg to Opts; now can specify exactly how many
  418. #          of the vars should be searched for in the environment.
  419. #          Check for duplicate rcfiles.
  420. # 96/05/13 Return more specific error values.  Note: ProcArgs() and InitOpts()
  421. #          now return various negatives values on error, not just -1, and
  422. #          Opts() may set Err to various positive values, not just 1.
  423. #          Added AllowUnrecOpt.
  424. # 96/05/23 Check type given for & option
  425. # 96/06/15 Re-port to awk
  426. # 96/10/01 Moved file-reading code into ReadConfFile(), so that it can be
  427. #          used by other functions.
  428. # 96/10/15 Added OptChars
  429. # 96/11/01 Added exOpts arg to Opts()
  430. # 96/11/16 Added ; type
  431. # 96/12/08 Added Opt2Set() & Opt2Sets()
  432. # 96/12/27 Added CmdLineOpt()
  433.  
  434. # optlist is a string which contains all of the possible command line options.
  435. # A character followed by certain characters indicates that the option takes
  436. # an argument, with type as follows:
  437. # :    String argument
  438. # ;    Non-empty string argument
  439. # *    Floating point argument
  440. # (    Non-negative floating point argument
  441. # )    Positive floating point argument
  442. # #    Integer argument
  443. # <    Non-negative integer argument
  444. # >    Positive integer argument
  445. # The only difference the type of argument makes is in the runtime argument
  446. # error checking that is done.
  447.  
  448. # The & option is a special case used to get numeric options without the
  449. # user having to give an option character.  It is shorthand for [-+.0-9].
  450. # If & is included in optlist and an option string that begins with one of
  451. # these characters is seen, the value given to "&" will include the first
  452. # char of the option.  & must be followed by a type character other than ":"
  453. # or ";".
  454. # Note that if e.g. &> is given, an option of -.5 will produce an error.
  455.  
  456. # Strings in argv[] which begin with "-" or "+" are taken to be
  457. # strings of options, except that a string which consists solely of "-"
  458. # or "+" is taken to be a non-option string; like other non-option strings,
  459. # it stops the scanning of argv and is left in argv[].
  460. # An argument of "--" or "++" also stops the scanning of argv[] but is removed.
  461. # If an option takes an argument, the argument may either immediately
  462. # follow it or be given separately.
  463. # "-" and "+" options are treated the same.  "+" is allowed because most awks
  464. # take any -options to be arguments to themselves.  gawk 2.15 was enhanced to
  465. # stop scanning when it encounters an unrecognized option, though until 2.15.5
  466. # this feature had a flaw that caused problems in some cases.  See the OptChars
  467. # parameter to explicitly set the option-specifier characters.
  468.  
  469. # If an option that does not take an argument is given,
  470. # an index with its name is created in Options and its value is set to the
  471. # number of times it occurs in argv[].
  472.  
  473. # If an option that does take an argument is given, an index with its name is
  474. # created in Options and its value is set to the value of the argument given
  475. # for it, and Options[option-name,"count"] is (initially) set to the 1.
  476. # If an option that takes an argument is given more than once,
  477. # Options[option-name,"count"] is incremented, and the value is assigned to
  478. # the index (option-name,instance) where instance is 2 for the second occurance
  479. # of the option, etc.
  480. # In other words, the first time an option with a value is encountered, the
  481. # value is assigned to an index consisting only of its name; for any further
  482. # occurances of the option, the value index has an extra (count) dimension.
  483.  
  484. # The sequence number for each option found in argv[] is stored in
  485. # Options[option-name,"num",instance], where instance is 1 for the first
  486. # occurance of the option, etc.  The sequence number starts at 1 and is
  487. # incremented for each option, both those that have a value and those that
  488. # do not.  Options set from a config file have a value of 0 assigned to this.
  489.  
  490. # Options and their arguments are deleted from argv.
  491. # Note that this means that there may be gaps left in the indices of argv[].
  492. # If compress is nonzero, argv[] is packed by moving its elements so that
  493. # they have contiguous integer indices starting with 0.
  494. # Option processing will stop with the first unrecognized option, just as
  495. # though -- was given except that unlike -- the unrecognized option will not be
  496. # removed from ARGV[].  Normally, an error value is returned in this case.
  497. # If AllowUnrecOpt is true, it is not an error for an unrecognized option to
  498. # be found, so the number of remaining arguments is returned instead.
  499. # If OptChars is not a null string, it is the set of characters that indicate
  500. # that an argument is an option string if the string begins with one of the
  501. # characters.  A string consisting solely of two of the same option-indicator
  502. # characters stops the scanning of argv[].  The default is "-+".
  503. # argv[0] is not examined.
  504. # The number of arguments left in argc is returned.
  505. # If an error occurs, the global string OptErr is set to an error message
  506. # and a negative value is returned.
  507. # Current error values:
  508. # -1: option that required an argument did not get it.
  509. # -2: argument of incorrect type supplied for an option.
  510. # -3: unrecognized (invalid) option.
  511. function ProcArgs(argc,argv,OptList,Options,compress,AllowUnrecOpt,OptChars,
  512. ArgNum,ArgsLeft,Arg,ArgLen,ArgInd,Option,Pos,NumOpt,Value,HadValue,specGiven,
  513. NeedNextOpt,GotValue,OptionNum,Escape,dest,src,count,c,OptTerm,OptCharSet)
  514. {
  515. # ArgNum is the index of the argument being processed.
  516. # ArgsLeft is the number of arguments left in argv.
  517. # Arg is the argument being processed.
  518. # ArgLen is the length of the argument being processed.
  519. # ArgInd is the position of the character in Arg being processed.
  520. # Option is the character in Arg being processed.
  521. # Pos is the position in OptList of the option being processed.
  522. # NumOpt is true if a numeric option may be given.
  523.     ArgsLeft = argc
  524.     NumOpt = index(OptList,"&")
  525.     OptionNum = 0
  526.     if (OptChars == "")
  527.     OptChars = "-+"
  528.     while (OptChars != "") {
  529.     c = substr(OptChars,1,1)
  530.     OptChars = substr(OptChars,2)
  531.     OptCharSet[c]
  532.     OptTerm[c c]
  533.     }
  534.     for (ArgNum = 1; ArgNum < argc; ArgNum++) {
  535.     Arg = argv[ArgNum]
  536.     if (length(Arg) < 2 || !((specGiven = substr(Arg,1,1)) in OptCharSet))
  537.         break    # Not an option; quit
  538.     if (Arg in OptTerm) {
  539.         delete argv[ArgNum]
  540.         ArgsLeft--
  541.         break
  542.     }
  543.     ArgLen = length(Arg)
  544.     for (ArgInd = 2; ArgInd <= ArgLen; ArgInd++) {
  545.         Option = substr(Arg,ArgInd,1)
  546.         if (NumOpt && Option ~ /[-+.0-9]/) {
  547.         # If this option is a numeric option, make its flag be & and
  548.         # its option string flag position be the position of & in
  549.         # the option string.
  550.         Option = "&"
  551.         Pos = NumOpt
  552.         # Prefix Arg with a char so that ArgInd will point to the
  553.         # first char of the numeric option.
  554.         Arg = "&" Arg
  555.         ArgLen++
  556.         }
  557.         # Find position of flag in option string, to get its type (if any).
  558.         # Disallow & as literal flag.
  559.         else if (!(Pos = index(OptList,Option)) || Option == "&") {
  560.         if (AllowUnrecOpt) {
  561.             Escape = 1
  562.             break
  563.         }
  564.         else {
  565.             OptErr = "Invalid option: " specGiven Option
  566.             return -3
  567.         }
  568.         }
  569.  
  570.         # Find what the value of the option will be if it takes one.
  571.         # NeedNextOpt is true if the option specifier is the last char of
  572.         # this arg, which means that if the option requires a value it is
  573.         # the next arg.
  574.         if (NeedNextOpt = (ArgInd >= ArgLen)) { # Value is the next arg
  575.         if (GotValue = ArgNum + 1 < argc)
  576.             Value = argv[ArgNum+1]
  577.         }
  578.         else {    # Value is included with option
  579.         Value = substr(Arg,ArgInd + 1)
  580.         GotValue = 1
  581.         }
  582.  
  583.         if (HadValue = AssignVal(Option,Value,Options,
  584.         substr(OptList,Pos + 1,1),GotValue,"",++OptionNum,!NeedNextOpt,
  585.         specGiven)) {
  586.         if (HadValue < 0)    # error occured
  587.             return HadValue
  588.         if (HadValue == 2)
  589.             ArgInd++    # Account for the single-char value we used.
  590.         else {
  591.             if (NeedNextOpt) {    # option took next arg as value
  592.             delete argv[++ArgNum]
  593.             ArgsLeft--
  594.             }
  595.             break    # This option has been used up
  596.         }
  597.         }
  598.     }
  599.     if (Escape)
  600.         break
  601.     # Do not delete arg until after processing of it, so that if it is not
  602.     # recognized it can be left in ARGV[].
  603.     delete argv[ArgNum]
  604.     ArgsLeft--
  605.     }
  606.     if (compress != 0) {
  607.     dest = 1
  608.     src = argc - ArgsLeft + 1
  609.     for (count = ArgsLeft - 1; count; count--) {
  610.         ARGV[dest] = ARGV[src]
  611.         dest++
  612.         src++
  613.     }
  614.     }
  615.     return ArgsLeft
  616. }
  617.  
  618. # Assignment to values in Options[] occurs only in this function.
  619. # Option: Option specifier character.
  620. # Value: Value to be assigned to option, if it takes a value.
  621. # Options[]: Options array to return values in.
  622. # ArgType: Argument type specifier character.
  623. # GotValue: Whether any value is available to be assigned to this option.
  624. # Name: Name of option being processed.
  625. # OptionNum: Number of this option (starting with 1) if set in argv[],
  626. #     or 0 if it was given in a config file or in the environment.
  627. # SingleOpt: true if the value (if any) that is available for this option was
  628. #     given as part of the same command line arg as the option.  Used only for
  629. #     options from the command line.
  630. # specGiven is the option specifier character use, if any (e.g. - or +),
  631. # for use in error messages.
  632. # Global variables: OptErr
  633. # Return value: negative value on error, 0 if option did not require an
  634. # argument, 1 if it did & used the whole arg, 2 if it required just one char of
  635. # the arg.
  636. # Current error values:
  637. # -1: Option that required an argument did not get it.
  638. # -2: Value of incorrect type supplied for option.
  639. # -3: Bad type given for option &
  640. function AssignVal(Option,Value,Options,ArgType,GotValue,Name,OptionNum,
  641. SingleOpt,specGiven,  UsedValue,Err,NumTypes) {
  642.     # If option takes a value...    [
  643.     NumTypes = "*()#<>]"
  644.     if (Option == "&" && ArgType !~ "[" NumTypes) {    # ]
  645.     OptErr = "Bad type given for & option"
  646.     return -3
  647.     }
  648.  
  649.     if (UsedValue = (ArgType ~ "[:;" NumTypes)) {    # ]
  650.     if (!GotValue) {
  651.         if (Name != "")
  652.         OptErr = "Variable requires a value -- " Name
  653.         else
  654.         OptErr = "option requires an argument -- " Option
  655.         return -1
  656.     }
  657.     if ((Err = CheckType(ArgType,Value,Option,Name,specGiven)) != "") {
  658.         OptErr = Err
  659.         return -2
  660.     }
  661.     # Mark this as a numeric variable; will be propogated to Options[] val.
  662.     if (ArgType != ":" && ArgType != ";")
  663.         Value += 0
  664.     if ((Instance = ++Options[Option,"count"]) > 1)
  665.         Options[Option,Instance] = Value
  666.     else
  667.         Options[Option] = Value
  668.     }
  669.     # If this is an environ or rcfile assignment & it was given a value...
  670.     else if (!OptionNum && Value != "") {
  671.     UsedValue = 1
  672.     # If the value is "0" or "-" and this is the first instance of it,
  673.     # do not set Options[Option]; this allows an assignment in an rcfile to
  674.     # turn off an option (for the simple "Option in Options" test) in such
  675.     # a way that it cannot be turned on in a later file.
  676.     if (!(Option in Options) && (Value == "0" || Value == "-"))
  677.         Instance = 1
  678.     else
  679.         Instance = ++Options[Option]
  680.     # Save the value even though this is a flag
  681.     Options[Option,Instance] = Value
  682.     }
  683.     # If this is a command line flag and has a - following it in the same arg,
  684.     # it is being turned off.
  685.     else if (OptionNum && SingleOpt && substr(Value,1,1) == "-") {
  686.     UsedValue = 2
  687.     if (Option in Options)
  688.         Instance = ++Options[Option]
  689.     else
  690.         Instance = 1
  691.     Options[Option,Instance]
  692.     }
  693.     # If this is a flag assignment without a value, increment the count for the
  694.     # flag unless it was turned off.  The indicator for a flag being turned off
  695.     # is that the flag index has not been set in Options[] but it has an
  696.     # instance count.
  697.     else if (Option in Options || !((Option,1) in Options))
  698.     # Increment number of times this flag seen; will inc null value to 1
  699.     Instance = ++Options[Option]
  700.     Options[Option,"num",Instance] = OptionNum
  701.     return UsedValue
  702. }
  703.  
  704. # Option is the option letter
  705. # Value is the value being assigned
  706. # Name is the var name of the option, if any
  707. # ArgType is one of:
  708. # :    String argument
  709. # ;    Non-null string argument
  710. # *    Floating point argument
  711. # (    Non-negative floating point argument
  712. # )    Positive floating point argument
  713. # #    Integer argument
  714. # <    Non-negative integer argument
  715. # >    Positive integer argument
  716. # specGiven is the option specifier character use, if any (e.g. - or +),
  717. # for use in error messages.
  718. # Returns null on success, err string on error
  719. function CheckType(ArgType,Value,Option,Name,specGiven,  Err,ErrStr) {
  720.     if (ArgType == ":")
  721.     return ""
  722.     if (ArgType == ";") {
  723.     if (Value == "")
  724.         Err = "must be a non-empty string"
  725.     }
  726.     # A number begins with optional + or -, and is followed by a string of
  727.     # digits or a decimal with digits before it, after it, or both
  728.     else if (Value !~ /^[-+]?([0-9]+|[0-9]*\.[0-9]+|[0-9]+\.)$/)
  729.     Err = "must be a number"
  730.     else if (ArgType ~ "[#<>]" && Value ~ /\./)
  731.     Err = "may not include a fraction"
  732.     else if (ArgType ~ "[()<>]" && Value < 0)
  733.     Err = "may not be negative"
  734.     # (
  735.     else if (ArgType ~ "[)>]" && Value == 0)
  736.     Err = "must be a positive number"
  737.     if (Err != "") {
  738.     ErrStr = "Bad value \"" Value "\".  Value assigned to "
  739.     if (Name != "")
  740.         return ErrStr "variable " substr(Name,1,1) " " Err
  741.     else {
  742.         if (Option == "&")
  743.         Option = Value
  744.         return ErrStr "option " specGiven substr(Option,1,1) " " Err
  745.     }
  746.     }
  747.     else
  748.     return ""
  749. }
  750.  
  751. # Note: only the above functions are needed by ProcArgs.
  752. # The rest of these functions call ProcArgs() and also do other
  753. # option-processing stuff.
  754.  
  755. # Opts: Process command line arguments.
  756. # Opts processes command line arguments using ProcArgs()
  757. # and checks for errors.  If an error occurs, a message is printed
  758. # and the program is exited.
  759. #
  760. # Input variables:
  761. # Name is the name of the program, for error messages.
  762. # Usage is a usage message, for error messages.
  763. # OptList the option description string, as used by ProcArgs().
  764. # MinArgs is the minimum number of non-option arguments that this
  765. # program should have, non including ARGV[0] and +h.
  766. # If the program does not require any non-option arguments,
  767. # MinArgs should be omitted or given as 0.
  768. # rcFiles, if given, is a colon-seprated list of filenames to read for
  769. # variable initialization.  If a filename begins with ~/, the ~ is replaced
  770. # by the value of the environment variable HOME.  If a filename begins with
  771. # $, the part from the character after the $ up until (but not including)
  772. # the first character not in [a-zA-Z0-9_] will be searched for in the
  773. # environment; if found its value will be substituted, if not the filename will
  774. # be discarded.
  775. # rcfiles are read in the order given.
  776. # Values given in them will not override values given on the command line,
  777. # and values given in later files will not override those set in earlier
  778. # files, because AssignVal() will store each with a different instance index.
  779. # The first instance of each variable, either on the command line or in an
  780. # rcfile, will be stored with no instance index, and this is the value
  781. # normally used by programs that call this function.
  782. # VarNames is a comma-separated list of variable names to map to options,
  783. # in the same order as the options are given in OptList.
  784. # If EnvSearch is given and nonzero, the first EnvSearch variables will also be
  785. # searched for in the environment.  If set to -1, all values will be searched
  786. # for in the environment.  Values given in the environment will override
  787. # those given in the rcfiles but not those given on the command line.
  788. # NoRCopt, if given, is an additional letter option that if given on the
  789. # command line prevents the rcfiles from being read.
  790. # See ProcArgs() for a description of AllowUnRecOpt and optChars, and
  791. # ExclusiveOptions() for a description of exOpts.
  792. # Special options:
  793. # If x is made an option and is given, some debugging info is output.
  794. # h is assumed to be the help option.
  795.  
  796. # Global variables:
  797. # The command line arguments are taken from ARGV[].
  798. # The arguments that are option specifiers and values are removed from
  799. # ARGV[], leaving only ARGV[0] and the non-option arguments.
  800. # The number of elements in ARGV[] should be in ARGC.
  801. # After processing, ARGC is set to the number of elements left in ARGV[].
  802. # The option values are put in Options[].
  803. # On error, Err is set to a positive integer value so it can be checked for in
  804. # an END block.
  805. # Return value: The number of elements left in ARGV is returned.
  806. # Must keep OptErr global since it may be set by InitOpts().
  807. function Opts(Name,Usage,OptList,MinArgs,rcFiles,VarNames,EnvSearch,NoRCopt,
  808. AllowUnrecOpt,optChars,exOpts,  ArgsLeft,e) {
  809.     if (MinArgs == "")
  810.     MinArgs = 0
  811.     ArgsLeft = ProcArgs(ARGC,ARGV,OptList NoRCopt,Options,1,AllowUnrecOpt,
  812.     optChars)
  813.     if (ArgsLeft < (MinArgs+1) && !("h" in Options)) {
  814.     if (ArgsLeft >= 0) {
  815.         OptErr = "Not enough arguments"
  816.         Err = 4
  817.     }
  818.     else
  819.         Err = -ArgsLeft
  820.     printf "%s: %s.\nUse -h for help.\n%s\n",
  821.     Name,OptErr,Usage > "/dev/stderr"
  822.     exit 1
  823.     }
  824.     if (rcFiles != "" && (NoRCopt == "" || !(NoRCopt in Options)) &&
  825.     (e = InitOpts(rcFiles,Options,OptList,VarNames,EnvSearch)) < 0)
  826.     {
  827.     print Name ": " OptErr ".\nUse -h for help." > "/dev/stderr"
  828.     Err = -e
  829.     exit 1
  830.     }
  831.     if ((exOpts != "") && ((OptErr = ExclusiveOptions(exOpts,Options)) != ""))
  832.     {
  833.     printf "%s: Error: %s\n",Name,OptErr > "/dev/stderr"
  834.     Err = 1
  835.     exit 1
  836.     }
  837.     return ArgsLeft
  838. }
  839.  
  840. # ReadConfFile(): Read a file containing var/value assignments, in the form
  841. # <variable-name><assignment-char><value>.
  842. # Whitespace (spaces and tabs) around a variable (leading whitespace on the
  843. # line and whitespace between the variable name and the assignment character) 
  844. # is stripped.  Lines that do not contain an assignment operator or which
  845. # contain a null variable name are ignored, other than possibly being noted in
  846. # the return value.  If more than one assignment is made to a variable, the
  847. # first assignment is used.
  848. # Input variables:
  849. # File is the file to read.
  850. # Comment is the line-comment character.  If it is found as the first non-
  851. #     whitespace character on a line, the line is ignored.
  852. # Assign is the assignment string.  The first instance of Assign on a line
  853. #     separates the variable name from its value.
  854. # If StripWhite is true, whitespace around the value (whitespace between the
  855. #     assignment char and trailing whitespace on the line) is stripped.
  856. # VarPat is a pattern that variable names must match.  
  857. #     Example: "^[a-zA-Z][a-zA-Z0-9]+$"
  858. # If FlagsOK is true, variables are allowed to be "set" by being put alone on
  859. #     a line; no assignment operator is needed.  These variables are set in
  860. #     the output array with a null value.  Lines containing nothing but
  861. #     whitespace are still ignored.
  862. # Output variables:
  863. # Values[] contains the assignments, with the indexes being the variable names
  864. #     and the values being the assigned values.
  865. # Lines[] contains the line number that each variable occured on.  A flag set
  866. #     is record by giving it an index in Lines[] but not in Values[].
  867. # Return value:
  868. # If any errors occur, a string consisting of descriptions of the errors
  869. # separated by newlines is returned.  In no case will the string start with a
  870. # numeric value.  If no errors occur,  the number of lines read is returned.
  871. function ReadConfigFile(Values,Lines,File,Comment,Assign,StripWhite,VarPat,
  872. FlagsOK,
  873. Line,Status,Errs,AssignLen,LineNum,Var,Val) {
  874.     if (Comment != "")
  875.     Comment = "^" Comment
  876.     AssignLen = length(Assign)
  877.     if (VarPat == "")
  878.     VarPat = "."    # null varname not allowed
  879.     while ((Status = (getline Line < File)) == 1) {
  880.     LineNum++
  881.     sub("^[ \t]+","",Line)
  882.     if (Line == "")        # blank line
  883.         continue
  884.     if (Comment != "" && Line ~ Comment)
  885.         continue
  886.     if (Pos = index(Line,Assign)) {
  887.         Var = substr(Line,1,Pos-1)
  888.         Val = substr(Line,Pos+AssignLen)
  889.         if (StripWhite) {
  890.         sub("^[ \t]+","",Val)
  891.         sub("[ \t]+$","",Val)
  892.         }
  893.     }
  894.     else {
  895.         Var = Line    # If no value, var is entire line
  896.         Val = ""
  897.     }
  898.     if (!FlagsOK && Val == "") {
  899.         Errs = Errs \
  900.         sprintf("\nBad assignment on line %d of file %s: %s",
  901.         LineNum,File,Line)
  902.         continue
  903.     }
  904.     sub("[ \t]+$","",Var)
  905.     if (Var !~ VarPat) {
  906.         Errs = Errs sprintf("\nBad variable name on line %d of file %s: %s",
  907.         LineNum,File,Var)
  908.         continue
  909.     }
  910.     if (!(Var in Lines)) {
  911.         Lines[Var] = LineNum
  912.         if (Pos)
  913.         Values[Var] = Val
  914.     }
  915.     }
  916.     if (Status)
  917.     Errs = Errs "\nCould not read file " File
  918.     close(File)
  919.     return Errs == "" ? LineNum : substr(Errs,2)    # Skip first newline
  920. }
  921.  
  922. # Variables:
  923. # Data is stored in Options[].
  924. # rcFiles, OptList, VarNames, and EnvSearch are as as described for Opts().
  925. # Global vars:
  926. # Sets OptErr.  Uses ENVIRON[].
  927. # If anything is read from any of the rcfiles, sets READ_RCFILE to 1.
  928. function InitOpts(rcFiles,Options,OptList,VarNames,EnvSearch,
  929. Line,Var,Pos,Vars,Map,CharOpt,NumVars,TypesInd,Types,Type,Ret,i,rcFile,
  930. fNames,numrcFiles,filesRead,Err,Values,retStr) {
  931.     split("",filesRead,"")    # make awk know this is an array
  932.     NumVars = split(VarNames,Vars,",")
  933.     TypesInd = Ret = 0
  934.     if (EnvSearch == -1)
  935.     EnvSearch = NumVars
  936.     for (i = 1; i <= NumVars; i++) {
  937.     Var = Vars[i]
  938.     CharOpt = substr(OptList,++TypesInd,1)
  939.     if (CharOpt ~ "^[:;*()#<>&]$")
  940.         CharOpt = substr(OptList,++TypesInd,1)
  941.     Map[Var] = CharOpt
  942.     Types[Var] = Type = substr(OptList,TypesInd+1,1)
  943.     # Do not overwrite entries from environment
  944.     if (i <= EnvSearch && Var in ENVIRON &&
  945.     (Err = AssignVal(CharOpt,ENVIRON[Var],Options,Type,1,Var,0)) < 0)
  946.         return Err
  947.     }
  948.  
  949.     numrcFiles = split(rcFiles,fNames,":")
  950.     for (i = 1; i <= numrcFiles; i++) {
  951.     rcFile = fNames[i]
  952.     if (rcFile ~ "^~/")
  953.         rcFile = ENVIRON["HOME"] substr(rcFile,2)
  954.     else if (rcFile ~ /^\$/) {
  955.         rcFile = substr(rcFile,2)
  956.         match(rcFile,"^[a-zA-Z0-9_]*")
  957.         envvar = substr(rcFile,1,RLENGTH)
  958.         if (envvar in ENVIRON)
  959.         rcFile = ENVIRON[envvar] substr(rcFile,RLENGTH+1)
  960.         else
  961.         continue
  962.     }
  963.     if (rcFile in filesRead)
  964.         continue
  965.     # rcfiles are liable to be given more than once, e.g. UHOME and HOME
  966.     # may be the same
  967.     filesRead[rcFile]
  968.     if ("x" in Options)
  969.         printf "Reading configuration file %s\n",rcFile > "/dev/stderr"
  970.     retStr = ReadConfigFile(Values,Lines,rcFile,"#","=",0,"",1)
  971.     if (retStr > 0)
  972.         READ_RCFILE = 1
  973.     else if (ret != "") {
  974.         OptErr = retStr
  975.         Ret = -1
  976.     }
  977.     for (Var in Lines)
  978.         if (Var in Map) {
  979.         if ((Err = AssignVal(Map[Var],
  980.         Var in Values ? Values[Var] : "",Options,Types[Var],
  981.         Var in Values,Var,0)) < 0)
  982.             return Err
  983.         }
  984.         else {
  985.         OptErr = sprintf(\
  986.         "Unknown var \"%s\" assigned to on line %d\nof file %s",Var,
  987.         Lines[Var],rcFile)
  988.         Ret = -1
  989.         }
  990.     }
  991.  
  992.     if ("x" in Options)
  993.     for (Var in Map)
  994.         if (Map[Var] in Options)
  995.         printf "(%s) %s=%s\n",Map[Var],Var,Options[Map[Var]] > \
  996.         "/dev/stderr"
  997.         else
  998.         printf "(%s) %s not set\n",Map[Var],Var > "/dev/stderr"
  999.     return Ret
  1000. }
  1001.  
  1002. # OptSets is a semicolon-separated list of sets of option sets.
  1003. # Within a list of option sets, the option sets are separated by commas.  For
  1004. # each set of sets, if any option in one of the sets is in Options[] AND any
  1005. # option in one of the other sets is in Options[], an error string is returned.
  1006. # If no conflicts are found, nothing is returned.
  1007. # Example: if OptSets = "ab,def,g;i,j", an error will be returned due to
  1008. # the exclusions presented by the first set of sets (ab,def,g) if:
  1009. # (a or b is in Options[]) AND (d, e, or f is in Options[]) OR
  1010. # (a or b is in Options[]) AND (g is in Options) OR
  1011. # (d, e, or f is in Options[]) AND (g is in Options)
  1012. # An error will be returned due to the exclusions presented by the second set
  1013. # of sets (i,j) if: (i is in Options[]) AND (j is in Options[]).
  1014. # todo: make options given on command line unset options given in config file
  1015. # todo: that they conflict with.
  1016. function ExclusiveOptions(OptSets,Options,
  1017. Sets,SetSet,NumSets,Pos1,Pos2,Len,s1,s2,c1,c2,ErrStr,L1,L2,SetSets,NumSetSets,
  1018. SetNum,OSetNum) {
  1019.     NumSetSets = split(OptSets,SetSets,";")
  1020.     # For each set of sets...
  1021.     for (SetSet = 1; SetSet <= NumSetSets; SetSet++) {
  1022.     # NumSets is the number of sets in this set of sets.
  1023.     NumSets = split(SetSets[SetSet],Sets,",")
  1024.     # For each set in a set of sets except the last...
  1025.     for (SetNum = 1; SetNum < NumSets; SetNum++) {
  1026.         s1 = Sets[SetNum]
  1027.         L1 = length(s1)
  1028.         for (Pos1 = 1; Pos1 <= L1; Pos1++)
  1029.         # If any of the options in this set was given, check whether
  1030.         # any of the options in the other sets was given.  Only check
  1031.         # later sets since earlier sets will have already been checked
  1032.         # against this set.
  1033.         if ((c1 = substr(s1,Pos1,1)) in Options)
  1034.             for (OSetNum = SetNum+1; OSetNum <= NumSets; OSetNum++) {
  1035.             s2 = Sets[OSetNum]
  1036.             L2 = length(s2)
  1037.             for (Pos2 = 1; Pos2 <= L2; Pos2++)
  1038.                 if ((c2 = substr(s2,Pos2,1)) in Options)
  1039.                 ErrStr = ErrStr "\n"\
  1040.                 sprintf("Cannot give both %s and %s options.",
  1041.                 c1,c2)
  1042.             }
  1043.     }
  1044.     }
  1045.     if (ErrStr != "")
  1046.     return substr(ErrStr,2)
  1047.     return ""
  1048. }
  1049.  
  1050. # The value of each instance of option Opt that occurs in Options[] is made an
  1051. # index of Set[].
  1052. # The return value is the number of instances of Opt in Options.
  1053. function Opt2Set(Options,Opt,Set,  count) {
  1054.     if (!(Opt in Options))
  1055.     return 0
  1056.     Set[Options[Opt]]
  1057.     count = Options[Opt,"count"]
  1058.     for (; count > 1; count--)
  1059.     Set[Options[Opt,count]]
  1060.     return count
  1061. }
  1062.  
  1063. # The value of each instance of option Opt that occurs in Options[] that
  1064. # begins with "!" is made an index of nSet[] (with the ! stripped from it).
  1065. # Other values are made indexes of Set[].
  1066. # The return value is the number of instances of Opt in Options.
  1067. function Opt2Sets(Options,Opt,Set,nSet,  count,aSet,ret) {
  1068.     ret = Opt2Set(Options,Opt,aSet)
  1069.     for (value in aSet)
  1070.     if (substr(value,1,1) == "!")
  1071.         nSet[substr(value,2)]
  1072.     else
  1073.         Set[value]
  1074.     return ret
  1075. }
  1076.  
  1077. # Returns true if option Opt was given on the command line.
  1078. function CmdLineOpt(Options,Opt,  i) {
  1079.     for (i = 1; (Opt,"num",i) in Options; i++)
  1080.     if (Options[Opt,"num",i] != 0)
  1081.         return 1
  1082.     return 0
  1083. }
  1084. ### End of ProcArgs library
  1085. # jhdiii 96/05/14
  1086. # Converts all of the elements of Arr with integer indices from Min to Max
  1087. # to a string of arguments individually quoted so that when passed to the
  1088. # shell as a command line to execute they will remain individual arguments and
  1089. # will not undergo any type of substitution.  Equivalent to "$@" in sh.
  1090. function QuoteArgs(Arr,Min,Max,  i,S,Arg) {
  1091.     for (i = Min; i <= Max; i++) {
  1092.     Arg = Arr[i]
  1093.     # Args are quoted with single-quotes.  To deal with single-quotes in
  1094.     # the arg, whereever one occurs, close the single-quotes, add a
  1095.     # backslash-escaped single quote, then re-open the single quotes.
  1096.     gsub("'","'\\''",Arg)
  1097.     S = S " '" Arg "'"
  1098.     }
  1099.     return substr(S,2)    # Lose initial space
  1100. }
  1101.